import os
import glob
import json
import time
import random
import string
import hashlib
import requests
import datetime
from django.http import Http404
from django.core.paginator import Paginator, EmptyPage

from utils.oss_helper import upload_file_to_oss2


def getmd5(t):
    md5_object = hashlib.md5()
    md5_object.update(t.encode())
    return str(md5_object.hexdigest())


def randomnk():
    nks = []
    while True:
        nk = set(random.sample(string.ascii_letters + string.digits, 8))
        if nk.intersection(string.ascii_uppercase) and nk.intersection(
                string.ascii_lowercase) and nk.intersection(string.digits):
            nks.append(''.join(nk))
        if len(nks) != 0:
            break
    return nks[0]


def randomactivecode():
    nks = []
    while True:
        nk = set(random.sample(string.ascii_letters + string.digits, 12))
        if nk.intersection(string.ascii_uppercase) and nk.intersection(
                string.ascii_lowercase) and nk.intersection(string.digits):
            nks.append(''.join(nk))
        if len(nks) != 0:
            break
    return nks[0]


def uploadtoserver(file, type=1):
    if file is None:
        return {
            "code": 1,
            "msg": "https://images.3games.io/web3/b1add95498cfbc853d8d359be996fc23.jpg"  # 暂无图片
        }
    extern = os.path.splitext(file.name)[1].lower()
    if type == 1:
        # if extern != '.jpg' and extern != '.png' and extern != '.gif':
        #     return {"code": 0, "msg": '图片格式不支持！'}
        if file.size > 4194304:
            return {"code": 0, "msg": '图片大小不能超过4兆！'}
    elif type == 2:
        if extern != '.mp4':
            return {"code": 0, "msg": '视频格式不支持！'}
        if file.size > 5242880:
            return {"code": 0, "msg": '视频大小不能超过5兆！'}

    filepath = upload_file_to_oss2(file.name, file.file.read(), None)

    return {
        "code": 1, "msg": filepath
    }


def getdjangopage(request, objs, size=15, nickname=None):
    paginator = Paginator(objs, size, )
    if paginator.num_pages <= 1:
        objs = objs
    else:
        page = int(request.GET.get('page', 1))

        try:
            objs = paginator.page(page)
        except EmptyPage:
            raise Http404("Page does not exist")

        left = []
        right = []
        last = False
        first = False
        left_has_more = False
        right_has_more = False
        page_range = paginator.page_range
        total_pages = paginator.num_pages

        if page == 1:
            right = page_range[page:page + 2]
            if right[-1] < total_pages - 1:
                right_has_more = True
            if right[-1] < total_pages:
                last = True
        elif page == total_pages:
            left = page_range[(page - 3) if (page - 3) > 0 else 0:page - 1]
            if left[0] > 2:
                left_has_more = True
            if left[0] > 1:
                first = True
        else:
            left = page_range[(page - 3) if (page - 3) > 0 else 0:page - 1]
            right = page_range[page:page + 2]
            if left[0] > 2:
                left_has_more = True
            if left[0] > 1:
                first = True
            if right[-1] < total_pages - 1:
                right_has_more = True
            if right[-1] < total_pages:
                last = True
        paginator = {
            'left': left,
            'last': last,
            'page': page,
            'right': right,
            'first': first,
            'total_pages': total_pages,
            'left_has_more': left_has_more,
            'right_has_more': right_has_more
        }
        if nickname: paginator['nickname'] = nickname
    return objs, paginator


def gettimedeltadate(days):
    return (datetime.date.today() + datetime.timedelta(days=days)).strftime("%Y-%m-%d")
